// 路由权限vuex模块

// 引入路由
import { constantRouters, asyncRouters, errorRouters } from "@/router"



const state = {
    // 最终结果,渲染左侧菜单栏
    routes: [],
    addRouters: [],//计算好的动态路由
    isGetUserInfo: false
}


// 计算单个路由是否有权限
const hasPermission = (route, role) => {
    if (route.meta?.roles) {
        return route.meta.roles.includes(role)
    } else {
        return true
    }
}

// 计算动态路由权限函数
const filterAsyncRouters = (routes, role) => {
    let temp = []
    routes.forEach(route => {
        if (hasPermission(route, role)) {
            //如果有儿子,儿子也需要计算
            if (route.children?.length) {
                route.children = filterAsyncRouters(route.children, role)
            }
            temp.push(route)
        }
    })
    return temp
}


const mutations = {
    ADD_ROUTERS(state, routes) {
        state.routes = [...constantRouters, ...routes]
    },
    SET_USERINFO_STATE(state, flag) {
        state.isGetUserInfo = flag
    }

}
const actions = {
    //生成动态路由函数
    generateRoutes({ commit }, role) {
        return new Promise(resolve => {
            // 筛选出可使用的动态路由
            let accessRoutes = filterAsyncRouters(asyncRouters, role)
            // 把accessRoutes存进vuex
            commit('ADD_ROUTERS', accessRoutes)
            // 把筛选好的动态路由和错误路由抛出去
            resolve([...accessRoutes, ...errorRouters])
        })
    }

}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}